package com.lh.cookie与session的研究;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * 作者：idea
 * 日期：2018/7/2
 * 描述：模拟用户登录的接口
 */
@WebServlet(name = "/login",urlPatterns = "/login")
public class UserLogin extends HttpServlet {



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies=req.getCookies();
        HttpSession session=req.getSession();
        PrintWriter out=resp.getWriter();
        Random random=new Random();
        int userId=random.nextInt(100);
        if(isFirstLogin(cookies)) {  //如果是第一次登录
            String key="uuid-token";
            String value=String.valueOf(System.currentTimeMillis());
            Cookie cookie=new Cookie(key,value);
            session.setAttribute(value,UserDb.userMap.get(userId));
            resp.addCookie(cookie);
        }
//        else{
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equals("token")) {
//                    String key = cookie.getValue();
//                    User user = (User) session.getAttribute(key);  //模拟存储的用户信息
//                    out.print(user.toString());
//                    break;
//                }
//            }
//        }
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


    private boolean isFirstLogin(Cookie[] cookies){
        boolean cookieStatus=true;
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("token")){
                cookieStatus=false;
            }
        }
        return cookieStatus;
    }
}
